package com.xiaotao.util;

import com.xiaotao.entity.User;
import com.xiaotao.mapper.UserMapper;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {
    @Resource
    private MinioClient minioClient;
    public Map<String, Object> uploadFile(MultipartFile file, String bucketName) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            map.put("code", 400);
            map.put("msg", "文件不能为空");
            return map;
        }
        boolean flag = minioClient.bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(bucketName);
        }
        String originalFilename = file.getOriginalFilename();
        String s = UUID.randomUUID().toString().replace("-", "");
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = s + substring;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMdd");
        String dirName = LocalDate.now().format(df);
        InputStream inputStream = file.getInputStream();
        PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(), -1);
        minioClient.putObject(bucketName, dirName + "/" + newFileName, inputStream, putObjectOptions);
        log.info("文件上传成功");
        map.put("code", 200);
        map.put("msg", "文件上传成功");
        String imageUrl = minioClient.getObjectUrl(bucketName, dirName + "/" + newFileName);
        map.put("imageUrl",imageUrl);
        return map;
    }
}
